package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"video-hub/cache"
	"video-hub/models"
)

func VideoList(c *gin.Context) {
	var videos []models.Video
	list_key := "list_key"
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Find(&videos)
		cachedata, _ := json.Marshal(videos)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &videos)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": videos,
	})
	return
}
func VideoDetail(c *gin.Context) {
	id := c.Query("id")
	detail_key := "detail_key" + id
	var video models.Video
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&video)
		cachedata, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &video)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	videoId, _ := strconv.Atoi(c.PostForm("video_id"))
	tx := models.DB.Begin()
	like := models.Like{
		UserId:  userId,
		VideoId: videoId,
	}
	err := tx.Create(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "点赞失败",
		})
		return
	}
	var video models.Video
	err = tx.First(&video, videoId).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "没有找到该视频",
		})
		return
	}
	video.LikeCount++
	err = tx.Save(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "点赞量更新失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "点赞成功",
		})
		return
	}
}
